//app.js
const ald = require('./utils/ald-stat.js')
import md5 from "./utils/md5.js"
let channel="Normal"
let distribution='Normal'
App({
  debug: false,
  onLaunch: function (options) {
    if (options.query.channel){
      channel = options.query.channel
    }
    if (options.query.scene && options.query.scene.indexOf('distribution') !== -1) {
      distribution = options.query.scene
    }
     let that=this;
    // 初次加载判断网络情况
    // 无网络状态下根据实际情况进行调整
    wx.getNetworkType({
      success: function(res) {
        const networkType= res.networkType
        if(networkType==='none'){
          that.globalData.isConnected=false
          wx.showToast({
            title: '当前无网络',
            icon:'loading',
            duration:2000,
            complete:function(){
              that.goStartIndexPage();
            }
          })
        }
      },
    })
    // 监听网络状态变化
    wx.onNetworkStatusChange(function(res){
      if(!res.isConnected){
        that.globalData.isConnected=false
        wx.showToast({
          title: '网络已断开',
          duration:2000,
          complete:function(){
            that.goStartIndexPage();
          }
        })
      }else{
        that.globalData.isConnected=true
        wx.hideToast()
      }
    })
    // 判断是否由分享进入小程序
    if (options.scene == 1007 || options.scene == 1008) {
      this.globalData.share = true
    } else {
      this.globalData.share = false
    };
  
    wx.updateShareMenu({
      withShareTicket:true
    })
    // 获取小程序更新机制兼容
    if (wx.canIUse('getUpdateManager')) {
      const updateManager = wx.getUpdateManager()
      updateManager.onCheckForUpdate(function (res) {
        // 请求完新版本信息的回调
        if (res.hasUpdate) {
          updateManager.onUpdateReady(function () {
            wx.showModal({
              title: '更新提示',
              content: '新版本已经准备好，是否重启应用？',
              success: function (res) {
                if (res.confirm) {
                  // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                  updateManager.applyUpdate()
                }
              }
            })
          })
          updateManager.onUpdateFailed(function () {
            // 新的版本下载失败
            wx.showModal({
              title: '已经有新版本了哟~',
              content: '新版本已经上线啦~，请您删除当前小程序，重新搜索打开哟~',
            })
          })
        }
      })
    } else {
      // 如果希望用户在最新版本的客户端上体验您的小程序，可以这样子提示
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
      })
    }
  },
  
  globalData: {
    //url: "https://uat.sbdj.shuigongbao.com/api/",//测试
    url: "https://sbdj.shuigongbao.com/api/",//正式
    appid: 'wx76fd9de923adad8c',
    userInfo:{},
    isPlayMusic:"",
    Music:"",
    share: false,  // 分享默认为false
    height: 0,
    myorderId:"",
    newRulesFlag: false,
    isConnected:true
  },
  //便捷的请求函数 可以自动登陆 应使用此函数访问接口
  request: function(api, params, needlogin) {
    let that=this;
    return new Promise(function(resolve, reject) {
      if (typeof(params) != "object") {
        params = {}
      }
      resolve(params)
    }).then(function(data) {
      return new Promise(function(resolve, reject) {
        if (typeof(needlogin) == "boolean" && needlogin) {
          getApp().get_token().then(function(token) {
            data.token = token
            resolve(data)
          })
        } else {
          resolve(data)
        }
      })
    }).then(function(data){
      return new Promise(function(resolve,reject){
        if (!data) {
          console.log('需要加密的数组对象为空')
        }
        var str = '';
        var secret = "qscguoefh..kijhyhi";
        if (!secret) {
          console.log('密钥未获取');
        }
        //生成key升序数组  
        var arr = Object.keys(data);
        arr.sort();
        for (var i in arr) {
          str += arr[i] + data[arr[i]];
        }
        // 截取前三
        let starStr = str.substring(0, 3);
        // 截取后三
        let endStr = str.substring(str.length - 2);
        // 加密url
        let secretUrl = md5(getApp().globalData.url + api);
        let sign = starStr + data.token + endStr + secretUrl;
        var encrypted = md5(sign + secret);
        data.sign = encrypted
        resolve(data)
      })
    }).then(function(data) {
      return getApp().request_api(api, data)
    })
  },
  get_token: function() { //获取登陆会话
    return new Promise(function(resolve, reject) {
      var token = wx.getStorageSync("token")
      var expire = wx.getStorageSync("expire")
      //检测是否已登录

      // if (token && Date.now() < expire && !getApp().debug) //会话存在且没有超时,无需登录
      if (token && !getApp().debug) //会话存在且没有超时,无需登录

      {
        resolve(token)
      } else { //需要登陆
        getApp().get_wx_login_code().then(function(code) {
          return getApp().request_api("applet/login", {
            code: code,
            channel:channel,
            distribution: distribution,
            applet:"shebaodaijiao100"
          },false)
        }).then(function(data) {
          if (data.code == 200) {
            var token = data.data.token;        
            wx.setStorageSync("token", token)
            wx.setStorageSync("expire", Date.now() + 60 * 60 * 1000)
            //上传用户信息
                // wx.getUserInfo({
                //   success: function(res) {
                //     var userInfo = res.userInfo
                //     let msg = {
                //       encrypteddata: res.encryptedData,
                //       iv: res.iv
                //     }
                //     getApp().request("update_userinfo2", msg, true);
                //     getApp().globalData.userInfo = res.userInfo;
                //   }
                // })
            resolve(token)
            // console.log("登录成功")
          } else {
            reject("登陆失败：无效的code")
            getApp().get_token();
          }
        })
      }
    })
  },
  get_wx_login_code: function() { //获取微信登陆code
    return new Promise(function(resolve, reject) {
      wx.login({
        success: function(res) {
          if (res.code) {
            // console.log(res)
            //发起网络请求
            resolve(res.code)
          } else {
            reject("获取登陆态失败")
          }
        },
        fail: function(err) {
          reject("登陆失败")
        }
      })
    })
  },
  //基本请求函数,会自动附加API所需的APPKEY
  request_api: function(api, data) {
    // console.log("excuting " + api, data)
    let that = this
    return new Promise(function(resolve, reject) {
      wx.request({
        url: getApp().globalData.url + api,
        data: data,
        method: "POST",
        header: {
          "Content-type": "application/x-www-form-urlencoded",
          'APIKEY': getApp().globalData.key
        },
        success: function(res) {
          console.log("result of " + api, res)
          if(res.statusCode == 404){
            wx.showModal({
              content:'404 NOT FOUND',
              showCancel:false
            })
            return
          }
          if(res.data.code == 500 && res.data.error_code == 1001){
            wx.removeStorageSync('token')
            that.goStartIndexPage()
            return
          }
          resolve(res.data)
        },
        fail: function(err) {
          console.log("请检查您的网络状态！");
        }
      })
    })
  },

  goStartIndexPage(){
    setTimeout(function(){
      const pages = getCurrentPages();
      const currentPage = pages[pages.length - 1]
      let route = currentPage.route;
      let query = JSON.stringify(currentPage.options);
      if(query){
        wx.reLaunch({
          url: `/pages/refresh/refresh?route=${route}&query=${query}`,
        })
      }else{
        wx.reLaunch({
          url: `/pages/refresh/refresh?route=${route}`,
        })
      }
    },1000)
  }

})